package clock.socoolby.com.clock.net.listener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import clock.socoolby.com.clock.net.base.I_JsonObject;
import clock.socoolby.com.clock.net.base.I_ResponseState;

public abstract class AbstractEntityListRequestListener<T extends I_JsonObject,Q extends I_ResponseState> extends AbstractJSONObjectRequestListener<T> {

    StateAbleRequestListener<List<T>,Q> warpListener;

    String arrayName;


    public AbstractEntityListRequestListener(String arrayName,StateAbleRequestListener<List<T>,Q> warpListener) {
        this.warpListener = warpListener;
        this.arrayName=arrayName;
    }

    @Override
    public void onResponse(JSONObject response) {
        super.onResponse(response);

        Q state= null;
        try {
            state = createState(response);
        } catch (JSONException e) {
            e.printStackTrace();
            state=null;
        }

        List<T> entity= new ArrayList<>();
        try {
            JSONArray entityArray=response.getJSONArray(arrayName);
            T temp;
            for(int i=0;i<entityArray.length();i++) {
                temp=creatEntity();
                temp.fromJson(entityArray.getJSONObject(i));
                entity.add(temp);
            }
        } catch (JSONException e) {
            e.printStackTrace();
            entity=null;
        }

        warpListener.onResponse(entity,state);
    }

    @Override
    public void onRequestFailed(int error, String errorMessage) {
        warpListener.onRequestFailed(error,errorMessage);
    }

    public abstract Q createState(JSONObject response) throws JSONException;
}
